package com.hzbat.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/***
 * socket 客户端请求工具类
 * @author yf141
 *
 */

public class SocketClientUtils {
	
    private static Logger logger = LoggerFactory.getLogger(SocketClientUtils.class);
	
    /***
     * 判断socket连接是否成功
     * @param ip
     * @param port
     * @return
     */
    public static boolean socketConnectStatus(String ip,String port){
		Socket socket = null;
		try {
			socket = new Socket(ip,Integer.valueOf(port));
			//连接成功
			return true ;
		} catch (Exception e) {
			//连接失败
			return false ;
		} finally{
			try {
				if(socket != null)
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
    
	/***
	 * 发送请求命令，返回字体串
	 * @param socket
	 * @param cmd
	 * @return
	 */
    public static String  sendDataCmd(String ip,String port,String cmd){
    	return sendDataCmd(ip,port,cmd,null);
    }	
 
	/***
	 * 发送请求命令，返回字体串
	 * @param socket
	 * @param cmd
	 * @param endFlag 结束标识
	 * @return
	 */
    public static String  sendDataCmd(String ip,String port,String cmd,String endFlag){
    	Socket socket= null ;
    	String response =null ;
		try {
			socket = new Socket(ip,Integer.valueOf(port));
			response = sendCmd(socket,cmd,endFlag);
		} catch (Exception e) {
			logger.error("socket通讯异常:"+ ip+":"+ port +"---->"+e);
			e.printStackTrace();
		}
    	return response ;
    }    
    
    /***
     * 发送请求命令，返回执行状态
     * @param socket
     * @param cmd
     * @return
     */
    public static boolean sendexecuteCmd(String ip,String port,String cmd){
    	return getResponseStatus(sendDataCmd(ip,port,cmd));
    }
    
    /***
     * 发送请求
     * @param cmd
     * @return
     */
    @SuppressWarnings("unused")
	private static String sendCmd(Socket socket,String cmd,String endFlag){
    	StringBuilder sb = new StringBuilder();
		OutputStream os = null ;
		BufferedReader br = null ;
    	try {
    		//socket.setSoTimeout(3000);
            os = socket.getOutputStream() ;
        	br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        	os.write(cmd.getBytes());
        	os.flush();
        	String str = null;
        	while((str=br.readLine())!=null){
        		if(endFlag != null && endFlag.equals(str.trim())){
        			logger.debug("读取到结束标识："+endFlag +"跳出循环");
        			break;
        		}
        		sb.append(str+"\n");
        	}
		} catch (Exception e) {
			logger.error("执行命令异常(cmd:"+ cmd +")----->"+e);
		}finally{
			close(socket,os,br);
		}
    	logger.info("执行cmd命令："+ cmd +"  返回响应结果："+sb.toString());
    	return sb.toString() ;
    }
   
    
    /***
     * 根据返回内容判断命令是否执行成功
	 * 返回内容不为空并且不包含“*** ERROR” 即为成功
     * @param response
     * @return
     */
    @SuppressWarnings("unused")
	private static boolean getResponseStatus( String response){
    	
    	return !StringUtil.isEmpty(response) && response.indexOf("*** ERROR")<0 ;
    	
    }
    
    
	/***
	 * 关闭Socket连接
	 * @param socket
	 * @param os
	 * @param br
	 */
    @SuppressWarnings("unused")
	private static void close(Socket socket,OutputStream os,BufferedReader br){
    		try {
    	    	if(socket != null ){
    	    		socket.close();
    	    	}
		    	if(os != null){
		    		os.close();
		    	}
		        if(br != null){
		        	br.close();
		        }
			} catch (Exception e) {
				logger.error("socket关闭异常---->"+e);;
			}
  

    }
    
	public static void main(String[] args) {
	    System.out.println("test----");
		System.out.println(sendDataCmd("158.1.0.55","11001","l h \n",">>"));

	}

}
